package ru.hh.school.commands;

import ru.hh.school.RoomManager;
import ru.hh.school.User;
import ru.hh.school.UserManager;
import ru.hh.school.exceptions.InnerChatException;
import ru.hh.school.logging.Logger;
import ru.hh.school.persistence.DataRepository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static ru.hh.school.util.ResourceManager.message;

public class ChatRouter {
    private final Map<String, Command> commands;
    private final Pattern validateCommand;

    public ChatRouter(RoomManager roomManager, UserManager userManager, DataRepository dataRepository, Logger logger) {
        this.commands = new HashMap<String, Command>();
        List<Command> commandsList = CommandLister.getCommandList(logger, userManager, dataRepository, roomManager);
        StringBuilder cmds = new StringBuilder();
        for (Command c : commandsList) {
            this.commands.put(c.getCommand(), c);
            cmds.append(c.getCommand()).append("|");
        }
        String pattern = "(" + cmds.deleteCharAt(cmds.length() - 1).toString() + ")(.*)";
        validateCommand = Pattern.compile(pattern);
    }

    public void command(User user, String message) throws InterruptedException {
        try {
            Matcher matcher = validateCommand.matcher(message);
            if (matcher.matches()) {
                String command = matcher.group(1);
                String data = matcher.group(2).trim();
                commands.get(command).handle(user, data);
            } else {
                user.sendMessage("Incorrect command");
            }
        } catch (InnerChatException e) {
            user.sendMessage(message("inner.error"));
        } catch (RuntimeException e) {
            user.sendMessage(message("inner.error"));
        }
    }
}